﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using EnvDTE80;

namespace MetaDrive.FluentCode
{
    public class FluentCodeEdit : IFluentCodeEdit 
    {
        public IFluentCodeElement Element { get; private set; }

        public EnvDTE.TextPoint StartPoint
        {
            get
            {
                return ((EnvDTE.CodeElement)Element.Adaptee).StartPoint;
            }
        }

        public EnvDTE.TextPoint EndPoint
        {
            get
            {
                return ((EnvDTE.CodeElement)Element.Adaptee).EndPoint;
            }
        }

        public string Body
        {
            get
            {
                TextPoint startBodyTextPoint = GetStartPoint(EnvDTE.vsCMPart.vsCMPartBody);
                TextPoint endBodyTextPoint = GetEndPoint(vsCMPart.vsCMPartBody);

                EditPoint2 ep = (EditPoint2)StartPoint.CreateEditPoint();
                ep.MoveToPoint(startBodyTextPoint);
                return ep.GetText(endBodyTextPoint);
            }
            set
            {
                TextPoint startBodyTextPoint = GetStartPoint(EnvDTE.vsCMPart.vsCMPartBody);
                TextPoint endBodyTextPoint = GetEndPoint(vsCMPart.vsCMPartBody);

                EditPoint2 ep = (EditPoint2)StartPoint.CreateEditPoint();
                ep.MoveToPoint(startBodyTextPoint);
                ep.ReplaceText(endBodyTextPoint, value, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
            }
        }

        public FluentCodeEdit(IFluentCodeElement element)
        {
            this.Element = element;
        }

        public EnvDTE.TextPoint GetStartPoint(EnvDTE.vsCMPart part)
        {            
            return ((EnvDTE.CodeElement)Element.Adaptee).GetStartPoint(part);
        }

        public EnvDTE.TextPoint GetEndPoint(EnvDTE.vsCMPart part)
        {
            return ((EnvDTE.CodeElement)Element.Adaptee).GetEndPoint(part);
        }
    }
}
